package com.example.algorithm.algorithmService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.algorithm.department.*;
import com.example.algorithm.mapper.*;
import com.example.algorithm.pojo.CityCoefficient;
import com.example.algorithm.pojo.DataInfo;
import com.example.algorithm.pojo.Department;

import com.example.algorithm.pojo.SvYdNumberSceneDO;
import com.example.algorithm.result.DepartmentControlMark;
import com.example.algorithm.result.PrintResult;
import com.example.algorithm.result.SupervisionScene;
import com.example.algorithm.utils.AreaJudgeUtils;
import com.example.algorithm.utils.GetDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class InspectorSceneService {

    @Resource
    private DataInfoMapper dataInfoMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Autowired
    private ControlAlgorithmService controlAlgorithmService;


    @Autowired
    private SupervisionSceneMapper supervisionSceneMapper;

    @Resource
    private SvYdNumberSceneMapper numberSceneMapper;

    @Autowired
    private  CityCoefficientMapper cityCoefficientMapper;

    public void getInspectorSceneIndex(String startDate, int num) throws ParseException {
        // 清空数据
        numberSceneMapper.delete(null);

        for (int i = 0; i < num; i++) {
            String start = GetDateUtils.manyDate(startDate, i);
            System.out.println(start);
            getControlMark(start);
        }
    }


    /**
     * 计算 督察场景清单指数
     *
     * @param startDate
     */
    private void getControlMark(String startDate) throws ParseException {
        String incrementDate = GetDateUtils.getIncrementDate(startDate);
        String stockDate = GetDateUtils.getStockDate(startDate);

        List<Department> departments = departmentMapper.selectList(null);

        // 定义7大督察场景
        //List<String> sceneList = Arrays.asList("领导视察督查", "领导批示督查", "领导交办督查", "重大决策督查", "重要会议督查", "民生实事督查", "建议提案督查");

        //List<String> sceneList = Arrays.asList("领导批示","领导交办","重大决策","民生实事","领导交办事项","重要会议","建议提案");

        // 获取7大督察场景
        List<String> sceneList = dataInfoMapper.selectSceneList();

        //各部门最终结果集合
        //List<DepartmentControlMark> resultList = new LinkedList();
        List<DepartmentControlMark> resultList = null;

        //城市系数
        List<CityCoefficient> cityCoefficients = cityCoefficientMapper.selectList(null);
        QueryWrapper<DataInfo> allDataInfoQuery = new QueryWrapper<>();
        allDataInfoQuery.lt("happen_date", incrementDate);
        allDataInfoQuery.gt("happen_date", stockDate);
        //2.查询所有数据
        List<DataInfo> allDataInfos = dataInfoMapper.selectList(allDataInfoQuery);

        //计算协作公共数据
        HashMap<String, DepartmentCoordination> coordinationPublicData = controlAlgorithmService.getCoordinationPublicData(allDataInfos);
        //计算牵头公共数据
        HashMap<String, DepartmentMainResponsibility> mainResponsibilityData = controlAlgorithmService.getMainResponsibilityCount(allDataInfos);

        //计算省协作次数
        List<Integer> provinceCoorList = new ArrayList<>();
        //计算省牵头次数
        List<Integer> provinceMainList = new ArrayList<>();

        //计算市协作次数
        List<Double> cityCoorList = new ArrayList<>();
        //计算市主体次数
        List<Double> cityMainList = new ArrayList<>();
        HashMap<Double,String> maxMainMap=new HashMap<>();
        HashMap<Double,String> maxCoorMap=new HashMap<>();
        controlAlgorithmService.computeCountList(provinceCoorList, provinceMainList, cityCoorList, cityMainList, coordinationPublicData, mainResponsibilityData,cityCoefficients,maxMainMap,maxCoorMap);

        //计算日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date parseDate = sdf.parse(startDate);

        for (String scene : sceneList) {
            resultList = new LinkedList();
            for (Department department : departments) {
                department = AreaJudgeUtils.getDepartMent(department.getDepName());

                //存量
                QueryWrapper<DataInfo> dataInfoQuery = new QueryWrapper<>();
                dataInfoQuery.like("duty_unit", department.getDepName());
                dataInfoQuery.eq("supervise_type", scene);
                dataInfoQuery.lt("happen_date", incrementDate);
                dataInfoQuery.gt("happen_date", stockDate);
                List<DataInfo> stockDataInfos = dataInfoMapper.selectList(dataInfoQuery);

                //增量
                QueryWrapper<DataInfo> dataInfoQuery2 = new QueryWrapper<>();
                dataInfoQuery2.like("duty_unit", department.getDepName());
                dataInfoQuery2.eq("supervise_type", scene);
                dataInfoQuery2.lt("happen_date", startDate);
                dataInfoQuery2.ge("happen_date", incrementDate);
                List<DataInfo> increaseDataInfos = dataInfoMapper.selectList(dataInfoQuery2);

                //无数据,跳过计算掌控力
                if (stockDataInfos.isEmpty() && increaseDataInfos.isEmpty()) {
                    continue;
                }
                ConcurrentHashMap<String, PrintResult> printResultMap = new ConcurrentHashMap<>();
                //问题主动发现指标
                Double initiativeDiscoveryMark = controlAlgorithmService.getInitiativeDiscoveryMark(stockDataInfos, department, printResultMap);

                //整改销号指标
                //Double reformMark = getReformMark(stockDataInfos);
                // modify 增加时间判断
                Double reformMark = controlAlgorithmService.getReformMarkNew(stockDataInfos,department,cityCoefficients, printResultMap);

                //问题整改协同率

                //  Double questionReformMark = controlAlgorithmService.getQuestionReformMark(department, coordinationPublicData, mainResponsibilityData, provinceCoorList, provinceMainList, cityCoorList, cityMainList);
                Double questionReformMark = 20d;

                //被动发现指标
                Double passiveDiscoveryMark = controlAlgorithmService.getPassiveDiscoveryMark(increaseDataInfos, department, printResultMap);

                //再发复发
                Double recrudesceMark = controlAlgorithmService.getRecrudesce(increaseDataInfos, department, printResultMap);

                //重大问题脱漏管指标
                SeriousProblemIgnore seriousProblemIgnoreMark1 = controlAlgorithmService.getSeriousProblemIgnoreMark(increaseDataInfos, department,cityCoefficients, printResultMap);
                Double seriousProblemIgnoreMark = seriousProblemIgnoreMark1.getSeriousProblemIgnoreMark();

                //即知即改
                Double immediateChangeScore = controlAlgorithmService.getImmediateChangeScore(questionReformMark);

                //整改到位
                Double reformGoodScore = controlAlgorithmService.getReformGoodScore(reformMark);

                //主动发现
                Double activeDiscoveryScore = controlAlgorithmService.getActiveDiscoveryScore(initiativeDiscoveryMark, passiveDiscoveryMark);

                //举一反三
                Double drawInferencesScore = controlAlgorithmService.getDrawInferencesScore(recrudesceMark, seriousProblemIgnoreMark);



                // System.out.println(department.getDepName() + JSONObject.toJSONString(seriousProblemIgnoreMark1.getDeductions()));

                //存量问题整改指数
                Double stockScore = initiativeDiscoveryMark + reformMark + questionReformMark;

                //增量问题新发指数
                Double repeatScore = passiveDiscoveryMark + recrudesceMark + seriousProblemIgnoreMark;

                //管控力
                Double controlPowerScore = stockScore + repeatScore;


                //五项之和
                Double tempSum = immediateChangeScore + reformGoodScore + activeDiscoveryScore + drawInferencesScore ;
                //各部门每日最终结果
                DepartmentControlMark controlMark = new DepartmentControlMark();
                controlMark.setReformMark(reformMark);
                controlMark.setInitiativeDiscoveryMark(initiativeDiscoveryMark);
                controlMark.setQuestionReformMark(questionReformMark);
                controlMark.setSeriousProblemIgnoreMark(seriousProblemIgnoreMark);
                controlMark.setPassiveDiscoveryMark(passiveDiscoveryMark);
                controlMark.setRecrudesceMark(recrudesceMark);
                controlMark.setStockScore(stockScore);
                controlMark.setRepeatScore(repeatScore);
                controlMark.setControlPowerScore(controlPowerScore);
                controlMark.setComputeDate(parseDate);
                controlMark.setImmediateChangeScore(immediateChangeScore);
                controlMark.setReformGoodScore(reformGoodScore);
                controlMark.setActiveDiscoveryScore(activeDiscoveryScore);
                controlMark.setDrawInferencesScore(drawInferencesScore);
                controlMark.setTempSum(tempSum);
                resultList.add(controlMark);

            }

            if (resultList.size() > 0) {
                double controlPowerScore = 0d;
                OptionalDouble average = resultList.stream().mapToDouble(DepartmentControlMark::getControlPowerScore).average();
                if (average.isPresent()) {
                    controlPowerScore = average.getAsDouble();
                }
                double reformMark = 0d;
                OptionalDouble average1 = resultList.stream().mapToDouble(DepartmentControlMark::getReformMark).average();
                if (average1.isPresent()) {
                    reformMark = average1.getAsDouble();
                }
                double initiativeDiscoveryMark = 0d;
                OptionalDouble average2 = resultList.stream().mapToDouble(DepartmentControlMark::getInitiativeDiscoveryMark).average();
                if (average2.isPresent()) {
                    initiativeDiscoveryMark = average2.getAsDouble();
                }
                double questionReformMark = 0d;
                OptionalDouble average3 = resultList.stream().mapToDouble(DepartmentControlMark::getQuestionReformMark).average();
                if (average3.isPresent()) {
                    questionReformMark = average3.getAsDouble();
                }

                double seriousProblemIgnoreMark = 0d;
                OptionalDouble average4 = resultList.stream().mapToDouble(DepartmentControlMark::getSeriousProblemIgnoreMark).average();
                if (average4.isPresent()) {
                    seriousProblemIgnoreMark = average4.getAsDouble();
                }
                double passiveDiscoveryMark = 0d;
                OptionalDouble average5 = resultList.stream().mapToDouble(DepartmentControlMark::getPassiveDiscoveryMark).average();
                if (average5.isPresent()) {
                    passiveDiscoveryMark = average5.getAsDouble();
                }
                double stockScore = 0d;
                OptionalDouble average6 = resultList.stream().mapToDouble(DepartmentControlMark::getStockScore).average();
                if (average6.isPresent()) {
                    stockScore = average6.getAsDouble();
                }
                double recrudesceMark = 0d;
                OptionalDouble average7 = resultList.stream().mapToDouble(DepartmentControlMark::getRecrudesceMark).average();
                if (average7.isPresent()) {
                    recrudesceMark = average7.getAsDouble();
                }
                double repeatScore =0d;
                OptionalDouble average8 = resultList.stream().mapToDouble(DepartmentControlMark::getRepeatScore).average();
                if (average8.isPresent()) {
                    repeatScore = average8.getAsDouble();
                }

                double immediateChangeScore =0d;
                OptionalDouble average9 = resultList.stream().mapToDouble(DepartmentControlMark::getImmediateChangeScore).average();
                if (average9.isPresent()) {
                    immediateChangeScore = average9.getAsDouble();
                }
                double reformGoodScore =0d;
                OptionalDouble average10 = resultList.stream().mapToDouble(DepartmentControlMark::getReformGoodScore).average();
                if (average10.isPresent()) {
                    reformGoodScore = average10.getAsDouble();
                }
                double activeDiscoveryScore = 0d;
                OptionalDouble average11 = resultList.stream().mapToDouble(DepartmentControlMark::getActiveDiscoveryScore).average();
                if (average11.isPresent()) {
                    activeDiscoveryScore = average11.getAsDouble();
                }
                double drawInferencesScore =0d;
                OptionalDouble average12 = resultList.stream().mapToDouble(DepartmentControlMark::getDrawInferencesScore).average();
                if (average12.isPresent()) {
                    drawInferencesScore = average12.getAsDouble();
                }

                double tempSum =0d;
                OptionalDouble average14 = resultList.stream().mapToDouble(DepartmentControlMark::getTempSum).average();
                if (average14.isPresent()) {
                    tempSum = average14.getAsDouble();
                }
                SupervisionScene controlMark = new SupervisionScene();
                controlMark.setReformMark(reformMark);
                controlMark.setSupervision(scene);
                controlMark.setInitiativeDiscoveryMark(initiativeDiscoveryMark);
                controlMark.setQuestionReformMark(questionReformMark);
                controlMark.setSeriousProblemIgnoreMark(seriousProblemIgnoreMark);
                controlMark.setPassiveDiscoveryMark(passiveDiscoveryMark);
                controlMark.setRecrudesceMark(recrudesceMark);
                controlMark.setStockScore(stockScore);
                controlMark.setRepeatScore(repeatScore);
                controlMark.setControlPowerScore(controlPowerScore);
                controlMark.setComputeDate(parseDate);
                controlMark.setImmediateChangeScore(immediateChangeScore);
                controlMark.setReformGoodScore(reformGoodScore);
                controlMark.setActiveDiscoveryScore(activeDiscoveryScore);
                controlMark.setDrawInferencesScore(drawInferencesScore);
                controlMark.setTempSum(tempSum);
                supervisionSceneMapper.insert(controlMark);



            }

//todo
            if( resultList.size() > 0) {
                double controlPowerScore = resultList.stream()
                        .mapToDouble(DepartmentControlMark::getControlPowerScore).average().getAsDouble();

                SvYdNumberSceneDO ydNumberSceneDO = new SvYdNumberSceneDO();
                ydNumberSceneDO.setSceneName(scene);
                ydNumberSceneDO.setDate(parseDate);
                ydNumberSceneDO.setNumberOfDay(controlPowerScore);
                ydNumberSceneDO.setDataValid(1);
                numberSceneMapper.insert(ydNumberSceneDO);

            } else {
                SvYdNumberSceneDO ydNumberSceneDO = new SvYdNumberSceneDO();
                ydNumberSceneDO.setSceneName(scene);
                ydNumberSceneDO.setDate(parseDate);
                ydNumberSceneDO.setNumberOfDay(0d);
                ydNumberSceneDO.setDataValid(1);
                numberSceneMapper.insert(ydNumberSceneDO);
            }


            log.info("scene: {}, resultList: {}", scene, resultList);
        }

    }


}
